package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Employee employee, Long[] ids) {
        //添加的时候进行密码加密,同户名当盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());
        employeeMapper.insert(employee);
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertByEmpIdAndRoleId(employee.getId(), rid);
            }
        }
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void updateByPrimaryKey(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //先删除关系再更新
        employeeMapper.deleteByEmpId(employee.getId());
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertByEmpIdAndRoleId(employee.getId(), rid);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String name, String password) {
        //查询数据库中是否有能匹配上的数据
        Employee employee = employeeMapper.selectByUsernameAndPassword(name, password);
        if (employee == null) { //登录失败
            //通知调用者这里失败了
            throw new RuntimeException("账号或者密码不匹配");
        }
        return employee;
    }

    @Override
    public void judge(String oldPassword, String newPassword, Long id) {
        Employee employee = employeeMapper.selectByOldPasswordAndId(oldPassword, id);
        if (employee == null) {
            //密码错误,没有查询到数据
            throw new RuntimeException("密码错误");
        } else {
            employeeMapper.updateByNewPassword(newPassword, id);
        }

    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);

    }

    @Override
    public Workbook exportXls() {
        //创建excel文件
        Workbook workbook = new HSSFWorkbook();
        //创建sheet
        Sheet sheet = workbook.createSheet("员工名单");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建行(每个员工就是一行)
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            if(employee.getName()!=null){//不为空才设置进去,否则报错
                row.createCell(0).setCellValue(employee.getName());
            }
            if(employee.getEmail()!=null){
                row.createCell(1).setCellValue(employee.getEmail());
            }
            if(employee.getAge()!=null){
                row.createCell(2).setCellValue(employee.getAge());
            }
        }
        return workbook;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //标题行不需要读,索引从1开始,<=是因为最后一行也要读取
        for (int i = 1; i <= lastRowNum; i++) {
            //获取每一行
            Row row = sheet.getRow(i);
            String name = row.getCell(0).getStringCellValue();//文本格式的单元格
            //判断如果用户名是空，就不再往下读
            if (!StringUtils.hasLength(name.trim())) {
                return;
            }
            //创建对象
            Employee employee = new Employee();
            employee.setName(name);
            String email = row.getCell(1).getStringCellValue();
            if (!StringUtils.hasLength(email.trim())) {
                return;
            }
            employee.setEmail(email);
            //获取文本格式的单元格内容
            //判断单元格类型
            CellType cellType = row.getCell(2).getCellType();
            if(cellType.equals(cellType.STRING)){
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            }else{
                employee.setAge((int) row.getCell(2).getNumericCellValue());
            }

            //获取数值类型的单元格内容
            //double value = row.getCell(2).getNumericCellValue();
            //employee.setAge((int)value);
            //设置默认密码是1
            employee.setPassword("1");
            employeeMapper.insert(employee);
        }

    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }

}
